
local file = io.open(arg[1],"rb");
local out_file = io.open(arg[2],"wb");
local toMSB = toMSB or false;
assert(file);
assert(out_file);
local data = file:read('*a');
--flash的数据不用翻转
--sram 的数据需要翻转
--实际上应该由jtag脚本来决定是否翻转数据

--[[
len由两个字节组成
 len[15:8] = data[0]
 len[7:0]  = data[1]
]]
local zero_pos = data:find('\x00');
--local pos = 0xf6; --测试
local pos = zero_pos;

local MSB = {};
local _get_bit = function(v,pos)
    return (v>>pos)&1;
end
for i=0,0xff do
    MSB[i] =
        (_get_bit(i,0)<<7)|
        (_get_bit(i,1)<<6)|
        (_get_bit(i,2)<<5)|
        (_get_bit(i,3)<<4)|
        (_get_bit(i,4)<<3)|
        (_get_bit(i,5)<<2)|
        (_get_bit(i,6)<<1)|
        (_get_bit(i,7)<<0) ;
end

while(pos<#data)do
    local len = data:byte(pos)<<8;
    len = len + data:byte(pos+1);
    assert((len&0x7)==0,"data error!");
    len = len>>3;
    print(len);
    pos = pos + 2;
    local s = data:sub(pos,pos+len-1);
    if(toMSB)then
        --转为大端序
        local news = '';
        for k=1,#s do
            news = news .. string.char(MSB[s:byte(k)]);
        end
        s = news;
    end
    out_file:write(s);
    pos = pos + len;
end

